﻿<?PHP
/**
 * Данный модуль написан для компаний "теплоарт" и "элит дизайн"
 * галерея картинок
 *
 * @author A. Grouzdev
 * @package gallery
 */

define('FW_GALLERY_TBL_GALS','galleries');
define('FW_GALLERY_TBL_ITEMS','gallery_items');

define('FW_GALLERY_HTML',"gallery_tpl.html");
define('FW_GALLERY_VARNAME_GALID','galID');

include('config.gallery.php');
include('class.gallery.php');

define('FWAD_GALLERY_ACTION_DEFAULT',0);
define('FWAD_GALLERY_ACTION_VIEW',0);
define('FWAD_GALLERY_ACTION_GETALLGALS',1);
define('FWAD_GALLERY_ACTION_GETGALSCNT',2);
define('FWAD_GALLERY_ACTION_ADDGAL',3);
define('FWAD_GALLERY_ACTION_EDITGAL',4);
define('FWAD_GALLERY_ACTION_GETGAL',5);
define('FWAD_GALLERY_ACTION_ADDGALITEM',6);
define('FWAD_GALLERY_ACTION_GETGALITEMS',7);
define('FWAD_GALLERY_ACTION_GETGALITEMSCNT',8);
define('FWAD_GALLERY_ACTION_EDITGALITEM',9);
define('FWAD_GALLERY_ACTION_GETGALITEM',10);
define('FWAD_GALLERY_ACTION_REPLACEIMG',11);
define('FWAD_GALLERY_ACTION_GETGALTOPITEM',12);
define('FWAD_GALLERY_ACTION_DELITEM',13);
define('FWAD_GALLERY_ACTION_EDITIMAGE',14);
define('FWAD_GALLERY_ACTION_DELGAL',15);
define('FWAD_GALLERY_ACTION_SAVEORDER',16);
define('FWAD_GALLERY_ACTION_COPYIMAGES',17);

class ModuleGallery extends Module implements IRequestHandler
{
	public $gal = null;
	public $galID = -1;
	public $path_to = "";
	function __construct(&$PageController)
	{
		parent::__construct($PageController);
		$params['dir'] = $PageController->cfg['absolute_path'].'images/gallery/';
		$params['s_w'] = FW_GALLERY_SIZE_S_W;
		$params['s_h'] = FW_GALLERY_SIZE_S_H;
		$params['m_w'] = FW_GALLERY_SIZE_M_W;
		$params['m_h'] = FW_GALLERY_SIZE_M_H;
		$params['b_w'] = FW_GALLERY_SIZE_B_W;
		$params['b_h'] = FW_GALLERY_SIZE_B_H;
		$this->gal = new Gallery($this->controller->db,$params);
	}
	public function &GetPage(&$PageInfo,$url)
	{
		$this->galID = -1;
		if (isset($PageInfo[1]['url_ext_path']))
			$this->path_to = $PageInfo[1]['url_ext_path'].'/'.$PageInfo[1]['dir_name'].'/';
		else $this->path_to = '/'.$PageInfo[1]['dir_name'].'/';
		if (isset($_GET[FW_GALLERY_VARNAME_GALID]))
		{
			if (is_numeric($_GET[FW_GALLERY_VARNAME_GALID]))
				$this->galID = (int)$_GET[FW_GALLERY_VARNAME_GALID];
			else throw new fwException("Ошибка!!! не тот формат у переменной ".FW_GALLERY_VARNAME_GALID,0);
			$this->is_root = false;
		}
		else {
			if (	isset($PageInfo[1]['url_reminder']) &&
					($PageInfo[1]['url_reminder']!=='')
				)
			{
				$dir= explode('/',$PageInfo[1]['url_reminder']);
				$c = count($dir);
				if (($c>0) && is_numeric($dir[0])) {$this->galID = $dir[0];}
			}
		}
		//print_r($PageInfo);
		if ($this->galID<1)
		{
			header ("HTTP/1.1 404 Not Found");
    		exit;
		}
		$this->controller->tpl->assign("galID",$this->galID);

		$this->controller->LoadModule('partition');
		$page = $this->controller->Modules['partition']->GetChildPage($PageInfo[1]['parent_id'],$PageInfo[1]['left_id'],$PageInfo[1]['right_id'],$PageInfo[1]['level'],FW_GALLERY_HTML);

		if ($page===false) throw new fwException("Не найден шаблон для модуля 'галерея'");
		if (is_null($page['template'])) throw new fwException("Не установлен главный шаблон для подшаблона модуля 'галерея'");

		$this->controller->main_template = $page['template'];
		$this->controller->content_template = $this->controller->cfg['absolute_path'].FW_PAGES_DIR.$page['pageName'];
		$this->controller->tpl->caching = true; //false;

		$this->controller->tpl->assign("pathto",$this->path_to);
		$out = $this->controller->tpl->fetch($this->controller->content_template,"gallery_c_".$this->galID);
		//require_once('../../smarty/plugins/function.eval.php');
		require_once('./framework/smarty/plugins/function.eval.php');

		smarty_function_eval(array('var'=>$page['title'], 'assign'=>'title'), $this->controller->tpl);
		smarty_function_eval(array('var'=>$page['keywords'], 'assign'=>'keywords'), $this->controller->tpl);
		smarty_function_eval(array('var'=>$page['description'], 'assign'=>'description'), $this->controller->tpl);

		$this->controller->tpl->assign("content",$out);
		$this->controller->cache_id = "gallery_".$this->galID;

		$PageInfo[0] = &$page;
		return $PageInfo;
	}
}

class ModuleGalleryAdmin extends ModuleAdmin implements IRequestHandlerInstaller, IModuleSelfInstaller
{
	/**
	 * Галерея
	 *
	 * @var Gallery
	 */
	public $gal;
	/**
	 * Конструктор инициализирует экземпляр класса
	 *
	 * @param AdminController $AdminController
	 * @return PartitionAdmin
	 */
	function __construct(&$AdminController)
	{
		parent::__construct($AdminController);
		$this->gal = new Gallery($this->controller->db,$AdminController->cfg['absolute_path'].'images/gallery/');
	}

	public function GetPage($Query)
	{
		define('FWAD_GALLERY_TPL', $this->controller->cfg['fw_path']."modules/gallery/tpls/");
		$this->_requestHandler('FWAD_GALLERY_ACTION_',FWAD_GALLERY_ACTION_DEFAULT,$_GET);
		switch ($this->_action)
		{
			case FWAD_GALLERY_ACTION_VIEW:
				$this->controller->main_template = FWAD_MAIN_TPL;
				$this->controller->content_template = FWAD_GALLERY_TPL."index_tpl.html";
				//$this->_printTree();
				break;
			case FWAD_GALLERY_ACTION_ADDGAL:
				if ($this->_fixact==0)
				{
					$this->controller->main_template = FWAD_MAIN_TPL;
					$this->controller->content_template = FWAD_GALLERY_TPL."edit_gal_tpl.html";
				}
				elseif ($this->_fixact==1)
				{
					$this->_addGallery();
				}
				break;
			case FWAD_GALLERY_ACTION_EDITGAL:
				if ($this->_fixact==0)
				{
					$this->controller->tpl->assign('SIZE_S_W', isset($_COOKIE['SIZE_S_W'])?(int)$_COOKIE['SIZE_S_W']: (int)FW_GALLERY_SIZE_S_W);
					$this->controller->tpl->assign('SIZE_S_H', isset($_COOKIE['SIZE_S_H'])?(int)$_COOKIE['SIZE_S_H']: (int)FW_GALLERY_SIZE_S_H);
					$this->controller->tpl->assign('SIZE_M_W', isset($_COOKIE['SIZE_M_W'])?(int)$_COOKIE['SIZE_M_W']: (int)FW_GALLERY_SIZE_M_W);
					$this->controller->tpl->assign('SIZE_M_H', isset($_COOKIE['SIZE_M_H'])?(int)$_COOKIE['SIZE_M_H']: (int)FW_GALLERY_SIZE_M_H);
					$this->controller->tpl->assign('SIZE_B_W', isset($_COOKIE['SIZE_B_W'])?(int)$_COOKIE['SIZE_B_W']: (int)FW_GALLERY_SIZE_B_W);
					$this->controller->tpl->assign('SIZE_B_H', isset($_COOKIE['SIZE_B_H'])?(int)$_COOKIE['SIZE_B_H']: (int)FW_GALLERY_SIZE_B_H);
					
					
					 
					$this->controller->main_template = FWAD_GALLERY_TPL."edit_gal_tpl.html";//FWAD_MAIN_TPL;
					//$this->controller->content_template = FWAD_GALLERY_TPL."edit_gal_tpl.html";
					$this->controller->tpl->assign('id',$this->_id);
				}
				elseif ($this->_fixact==1)
				{
					$this->_editGallery();
				}
				break;
			case FWAD_GALLERY_ACTION_ADDGALITEM:
				$this->_addGalItem();
				break;
			case FWAD_GALLERY_ACTION_EDITGALITEM:
				if ($this->_fixact==0)
				{
					$this->controller->main_template = FWAD_MAIN_TPL;
					$this->controller->content_template = FWAD_GALLERY_TPL."edit_galitem_tpl.html";
					$this->controller->tpl->assign('id',$this->_id);
					if (isset($_GET['galid'])) 
						$this->controller->tpl->assign('galid', (int)$_GET['galid']);
					else 
						$this->controller->tpl->assign('galid',-1);
				}
				elseif ($this->_fixact==1)
				{
					$this->_editGalleryItem();
				}
				break;
			case FWAD_GALLERY_ACTION_REPLACEIMG:
				if ($this->_fixact==1)
				{
					$this->_replaceImg();
				}
				break;
			case FWAD_GALLERY_ACTION_DELITEM:
				if ($this->_fixact==1)
				{
					$this->_deleteImg();
				}
				break;
			case FWAD_GALLERY_ACTION_EDITIMAGE:
				if ($this->_fixact==1)
				{
					$this->_editImage();
				}
				else 
				{
					$this->controller->main_template = FWAD_POPUP_BLANK_TPL;
					$this->controller->content_template = FWAD_GALLERY_TPL."edit_img_tpl.html";
					$this->controller->tpl->assign('id',$this->_id);
					$it = $_GET['imageType'];														
					$this->controller->tpl->assign('imageType',$it); //1-мал 2-сред 3-бол
				}
				break;
			case FWAD_GALLERY_ACTION_DELGAL:
				if (is_array($_POST['id']))
				{
					foreach ($_POST['id'] as $id) {
						$this->gal->DeleteGallery((int) $id);
					}
				}
				else 
					$this->gal->DeleteGallery((int) $_POST['id']);
				$this->Success();
				break;
			case FWAD_GALLERY_ACTION_SAVEORDER:
				$this->_saveOrder();
				break;
			case FWAD_GALLERY_ACTION_COPYIMAGES:
				$this->_copyImage();
				break;
		}
	}
	public function Success()
	{
		$this->controller->tpl->assign('RedirectUrl','index.php?module=gallery');
		parent::Success();
	}
	private function _addGallery()
	{
		$params['name'] = addslashes($_POST['name']);
		$params['shortDescription'] = addslashes($_POST['shortDescription']);
		$params['description'] = addslashes($_POST['description']);
		$id = $this->gal->AddGallery($params);
		$this->controller->tpl->assign('RedirectUrl','index.php?module=gallery&action=editgal&id='.$id);
		parent::Success();
	}
	private function _editGallery()
	{
		$params['name'] = PrepareVar_4($_POST['name']);
		$params['shortDescription'] = PrepareVar_4($_POST['shortDescription']);
		$params['description'] = PrepareVar_4($_POST['description']);
		$this->gal->SetGallery($this->_id,$params);
		$this->Success();
	}
	private function _addGalItem()
	{
		$i=0;
		$sizes = array();
		$cookie = array();
		$watermark = array();
		while( isset($_FILES['userfile'.$i]))
		{
			$prop = array(
				'alt_text'=>addslashes($_POST['alt_text'.$i]),
				'description'=>addslashes($_POST['description'.$i])
			);
			$sizes['native'] = array();
			$sizes['small'] = array(
					isset($_POST['swidth_'.$i]) && ($_POST['swidth_'.$i]>0) ? (int)$_POST['swidth_'.$i] : (int)FW_GALLERY_SIZE_S_W,
					isset($_POST['sheight_'.$i]) && ($_POST['sheight_'.$i]>0) ? (int)$_POST['sheight_'.$i] : (int)FW_GALLERY_SIZE_S_H,
					's_'
					);
			$sizes['medium'] = array(
					isset($_POST['mwidth_'.$i]) && ($_POST['mwidth_'.$i]>0) ? (int)$_POST['mwidth_'.$i] : (int)FW_GALLERY_SIZE_M_W,
					isset($_POST['mheight_'.$i]) && ($_POST['mheight_'.$i]>0) ? (int)$_POST['mheight_'.$i]: (int)FW_GALLERY_SIZE_M_H,
					'm_'
					);
			$sizes['big'] = array(
					isset($_POST['bwidth_'.$i]) && ($_POST['bwidth_'.$i]>0)? (int)$_POST['bwidth_'.$i] : (int)FW_GALLERY_SIZE_B_W,
					isset($_POST['bheight_'.$i]) && ($_POST['bheight_'.$i]>0) ? (int)$_POST['bheight_'.$i]: (int)FW_GALLERY_SIZE_B_H,
					'b_'
					);
			
			$watermark['small'] = (isset($_POST['mus'.$i]))? array($this->gal->dir.FW_GALLERY_CR_MASK_FILE,1) : array();
			$watermark['medium'] = (isset($_POST['mum'.$i]))? array($this->gal->dir.FW_GALLERY_CR_MASK_FILE,1) : array();
			$watermark['big'] = (isset($_POST['mub'.$i]))? array($this->gal->dir.FW_GALLERY_CR_MASK_FILE,1) : array();
			
			try
			{
				if (($_FILES['userfile'.$i]['error']!=UPLOAD_ERR_NO_FILE) && ($this->gal->UploadGalleryItem($this->_id,'userfile'.$i,$prop,$sizes,$watermark)!==false))
				{
					$cookie['SIZE_S_W'] = $sizes['small'][0];
					$cookie['SIZE_S_H'] = $sizes['small'][1];
					$cookie['SIZE_M_W'] = $sizes['medium'][0];
					$cookie['SIZE_M_H'] = $sizes['medium'][1];
					$cookie['SIZE_B_W'] = $sizes['big'][0];
					$cookie['SIZE_B_H'] = $sizes['big'][1];
					$cookie['mask_small'] = isset ($watermark['small'][0]);
					$cookie['mask_medium'] = isset ($watermark['medium'][0]);
					$cookie['mask_big'] = isset ($watermark['big'][0]);
				}
			}
			catch (fwException $e)
			{
				echo "Во время загрузки произошли ошибки: ".$e->getMessage()."<br>\n";
			}
			$i++;
		}
		
		$expire = time()+60*60*24*30;
		$del = $expire-60*120*24*30;
		foreach ($cookie as $cookname => $cook) {
			setcookie($cookname,$cook,$expire);
		}
		/*foreach ($watermark as $thumb_type=>$mask)
		{
			if (isset($mask[0]) && ($mask[0]!="")) 
				setcookie('mask_'.$thumb_type,'1',$expire);
			else 
				setcookie('mask_'.$thumb_type,'0',$del);
		}
		*/
		$this->controller->tpl->assign('RedirectUrl','index.php?module=gallery&action=editgal&id='.$this->_id);
		parent::Success();
	}
	private function _replaceImg()
	{
		if (isset($_GET['type']) 
			&& (($_GET['type']=='s_')
			|| ($_GET['type']=='m_')
			|| ($_GET['type']=='b_')
			)
		)
			$name_prefix = $_GET['type'];
		else
			throw new fwException("Не установлен тип заменяемой картинки",0);
		
		$watermark_file = (isset($_POST['mu'])) ? $this->gal->dir.FW_GALLERY_CR_MASK_FILE : null;
		
		$this->gal->UploadItem($this->_id,'userfile',$name_prefix,$watermark_file);
		$this->Success();
	}
	private function _editGalleryItem()
	{
		$prop['alt_text'] = substr(addslashes($_POST['alt_text']),0,255);
		$prop['description'] = substr(addslashes($_POST['description']),0,255);
		$prop['n_w'] = (int)$_POST['n_w'];
		$prop['n_h'] = (int)$_POST['n_h'];
		$prop['s_w'] = (int)$_POST['s_w'];
		$prop['s_h'] = (int)$_POST['s_h'];
		$prop['m_w'] = (int)$_POST['m_w'];
		$prop['m_h'] = (int)$_POST['m_h'];
		$this->gal->SetGalleryItem($this->_id,$prop);
		if (isset($_GET['galid']) && ($_GET['galid']>-1))
		{
			
			$galid = (int)$_GET['galid'];
			$this->controller->tpl->assign('RedirectUrl','index.php?module=gallery&action=editgal&id='.$galid);
			parent::Success();
		}
		else
			$this->Success();
	}
	private function _deleteImg()
	{
		if (is_array($_POST['itemId']))
		{
			foreach ($_POST['itemId'] as $id) {
				try 
				{
					$this->gal->DeleteItem((int)$id,array('b_','s_','m_',''));
				}
				catch (FileSystemException $e)
				{
					
				}
			}
		}
		else 
			$this->gal->DeleteItem((int)$_POST['itemId']);
		$this->controller->tpl->assign('RedirectUrl','index.php?module=gallery&action=editgal&id='.$this->_id);
		parent::Success();
	}
	private function _copyImage()
	{
		if (is_array($_POST['itemId']))
		{
			foreach ($_POST['itemId'] as $id) {
				$info = $this->gal->GetGalleryItem($id);
				unset($info['id']);
				$new_id = $this->gal->AddGalleryItem( $this->_id, $info );
				copy($this->gal->dir.$id.'.'.$info['ext'],$this->gal->dir.$new_id.'.'.$info['ext']);
				copy($this->gal->dir.'m_'.$id.'.'.$info['ext'],$this->gal->dir.'m_'.$new_id.'.'.$info['ext']);
				copy($this->gal->dir.'s_'.$id.'.'.$info['ext'],$this->gal->dir.'s_'.$new_id.'.'.$info['ext']);
				copy($this->gal->dir.'n_'.$id.'.'.$info['ext'],$this->gal->dir.'n_'.$new_id.'.'.$info['ext']);
			}
		}
		else
		{
			$id = (int)$_POST['itemId'];
			$info = $this->gal->GetGalleryItem($id);
			unset($info['id']);
			$new_id = $this->gal->AddGalleryItem( $this->_id, $info );
			copy($this->gal->dir.$id.'.'.$info['ext'],$this->gal->dir.$new_id.'.'.$info['ext']);
			copy($this->gal->dir.'m_'.$id.'.'.$info['ext'],$this->gal->dir.'m_'.$new_id.'.'.$info['ext']);
			copy($this->gal->dir.'s_'.$id.'.'.$info['ext'],$this->gal->dir.'s_'.$new_id.'.'.$info['ext']);
			copy($this->gal->dir.'n_'.$id.'.'.$info['ext'],$this->gal->dir.'n_'.$new_id.'.'.$info['ext']);
		}
		$this->controller->tpl->assign('RedirectUrl','index.php?module=gallery&action=editgal&id='.$this->_id);
		parent::Success();
	}
	private function _editImage()
	{
		if (!isset($_GET['ot'])) throw new fwException("Не установлен тип открываемого файла",0);
		if (!isset($_GET['st'])) throw new fwException("Не установлен тип сохраняемого файла",0);
		
		$item = $this->gal->GetGalleryItem($this->_id);
		
		$openFile = "";
		$saveAsFile="";
		
		switch ($_GET['ot']) {
			case 1: $openFile = $this->controller->cfg['absolute_path'].'images/gallery/s_'.$this->_id.'.'.$item['ext']; break;
			case 2: $openFile = $this->controller->cfg['absolute_path'].'images/gallery/m_'.$this->_id.'.'.$item['ext']; break;
			case 3: $openFile = $this->controller->cfg['absolute_path'].'images/gallery/'.$this->_id.'.'.$item['ext']; break;
		}
		
		switch ($_GET['st']) {
			case 1: $saveAsFile = $this->controller->cfg['absolute_path'].'images/gallery/s_'.$this->_id.'.'.$item['ext']; break;
			case 2: $saveAsFile = $this->controller->cfg['absolute_path'].'images/gallery/m_'.$this->_id.'.'.$item['ext']; break;
			case 3: $saveAsFile = $this->controller->cfg['absolute_path'].'images/gallery/'.$this->_id.'.'.$item['ext']; break;
		}
		
		if (isset($_GET['size']))
		{
			$size = explode(',',$_GET['size'],2);
			$this->gal->ScaleImage($openFile,$saveAsFile,(int)$size[0],(int)$size[1]);
			$openFile = $saveAsFile;		
		}
		if (isset($_GET['crop']))
		{
			$crop = explode(',',$_GET['crop'],4);
			$this->gal->CropImage($openFile,$saveAsFile,$crop[0],$crop[1],$crop[2],$crop[3]);
		}
		list($w, $h) = getimagesize($saveAsFile);
		switch ($_GET['st']) {
			case 1: $p['s_w'] = $w; $p['s_h'] = $h; break;
			case 2: $p['m_w'] = $w; $p['m_h'] = $h; break;
			case 3: $p['n_w'] = $w; $p['n_h'] = $h; break;
		}
		$this->gal->SetGalleryItem($this->_id,$p);
		$this->Success();
	}
	private function _saveOrder()
	{
		$order=$_GET['ord'];
		$arr = explode(",",$order);
		for($i=0;$i<count($arr);$i++)
		{
			$this->gal->SetGalleryItem((int)$arr[$i],array('weight'=>$i));
		}
		$this->controller->tpl->assign('RedirectUrl','index.php?module=gallery&action=editgal&id='.$this->_id);
		parent::Success();
	}
	static function Install(&$cfg,&$db,$deleteTables)
	{
		if ($deleteTables)
		{
			$Result = $db->query('DROP TABLE IF EXISTS '.FW_DB_TBL_PREFIX.FW_GALLERY_TBL_GALS);
			if (PEAR::isError($Result))	
				throw new fwException($Result->getMessage(), $Result->getCode());
			$Result = $db->query('DROP TABLE IF EXISTS '.FW_DB_TBL_PREFIX.FW_GALLERY_TBL_ITEMS);
			if (PEAR::isError($Result))	
				throw new fwException($Result->getMessage(), $Result->getCode());
		}
		$Result = $db->query("CREATE TABLE ".FW_DB_TBL_PREFIX.FW_GALLERY_TBL_GALS." (
  `id` int(11) NOT NULL auto_increment,
  `name` varchar(255) default NULL,
  `shortDescription` varchar(255) default NULL,
  `description` tinytext,
  `weight` int(11) NOT NULL default '0',
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;");
		if (PEAR::isError($Result))
			throw new fwException($Result->getMessage(), $Result->getCode());
		$Result = $db->query("CREATE TABLE ".FW_DB_TBL_PREFIX.FW_GALLERY_TBL_ITEMS." (
  `id` int(11) NOT NULL auto_increment,
  `gal_id` int(11) NOT NULL default '0',
  `ext` varchar(4) default NULL,
  `alt_text` varchar(255) default NULL,
  `description` varchar(255) default NULL,
  `n_w` smallint(5) unsigned NOT NULL default '0',
  `n_h` smallint(5) unsigned NOT NULL default '0',
  `s_w` smallint(5) unsigned NOT NULL default '0',
  `s_h` smallint(5) unsigned NOT NULL default '0',
  `m_w` smallint(5) unsigned NOT NULL default '0',
  `m_h` smallint(5) unsigned NOT NULL default '0',
  `weight` int(11) NOT NULL default '0',
  PRIMARY KEY  (`id`),
  KEY `gal_id` (`gal_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;");
		if (PEAR::isError($Result))
			throw new fwException($Result->getMessage(), $Result->getCode());
	}
	
	public function OnSetExtension($params)
	{
		$this->controller->LoadModule('pages');
		
		$ID = $this->controller->Modules['pages']->AddFile("Шаблон для отображения картинок галереи");
		$this->controller->Modules['pages']->SetFile($ID,"1");
		
		$this->controller->LoadModule('partition');
		$this->controller->Modules['partition']->addDocument(FW_GALLERY_HTML,"","","",$ID,'NULL',$params['partID'],0);
		//echo "OnSetExtension";
	}
	public function OnUnsetExtension($params)
	{
		//echo "OnUnsetExtension";
	}
}

?>